package com.allwees.bs.c.common.auth;

import com.allwees.bs.c.common.auth.constant.EAuthType;
import com.allwees.bs.c.common.auth.model.OAuthUserInfo;
import com.allwees.bs.c.module.user.entity.UserEntity;
import com.allwees.bs.c.module.user.repository.UserRepository;
import com.allwees.bs.c.module.user.req.ThirdPartLoginReq;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

/**
 * AuthHandler  第三方支付处理器
 * Date: 2018/8/15
 * Time: 09:29
 *
 * @author tianye
 */
@Slf4j
public abstract class AuthHandler {
	@Resource
	protected UserRepository userDao;

	@Autowired
	protected PasswordEncoder passwordEncoder;

	@PostConstruct
	public void init() {
		AuthHandlerFactory.register(getAuthType(), this);
	}

	/**
	 * 获取认证类型
	 *
	 * @return 认证类型
	 */
	public abstract EAuthType getAuthType();

	/**
	 * 通过token获取用户信息
	 *
	 * @return 用户信息
	 */
	public abstract AuthResult auth(ThirdPartLoginReq loginReq);

	protected boolean completeUserInfo(UserEntity user,String email,String firstName,String lastName,String avatarUrl){
		boolean updated = false;
		if (StringUtils.isBlank(user.getEmail()) && StringUtils.isNotBlank(email)) {
			user.setEmail(email);
			updated = true;
		}
		if (StringUtils.isBlank(user.getFirstName()) && StringUtils.isNotBlank(firstName)) {
			user.setFirstName(firstName);
			updated = true;
		}
		if (StringUtils.isBlank(user.getLastName()) && StringUtils.isNotBlank(lastName)) {
			user.setLastName(lastName);
			updated = true;
		}
		if (StringUtils.isBlank(user.getAvatar()) && StringUtils.isNotBlank(avatarUrl)) {
			user.setAvatar(avatarUrl);
			updated = true;
		}
		return updated;
	}

	protected AuthResult auth(UserEntity user, OAuthUserInfo oauthUserInfo,boolean save) {
		boolean isNewUser = false;
		if(user == null) {
			isNewUser = true;
			save = true;
			user = oauthUserInfo.toUserEntity(passwordEncoder);
		}
		AuthResult authResult = new AuthResult(user, isNewUser, save);
		authResult.setOauthUserInfo(oauthUserInfo);
		return authResult;
	}
}
